package com.netty.chatRoom.server.Handler;

import com.netty.chatRoom.message.LoginRequestMessage;
import com.netty.chatRoom.message.LoginResponseMessage;
import com.netty.chatRoom.server.service.UserServiceFactory;
import com.netty.chatRoom.server.session.SessionFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
@ChannelHandler.Sharable
public class LoginRequestMessageHandler extends SimpleChannelInboundHandler<LoginRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, LoginRequestMessage loginRequestMessage) throws Exception {
        // 获取到登录的请求消息
        String username = loginRequestMessage.getUsername();
        String password = loginRequestMessage.getPassword();
        boolean flag = UserServiceFactory.getUserService().login(username, password);
        LoginResponseMessage responseMessage = null;
        if (flag) {
            // 在服务器中保存会话信息
            SessionFactory.getSession().bind(channelHandlerContext.channel(), username);
            responseMessage = new LoginResponseMessage(flag, "登录成功！");
        } else {
            responseMessage = new LoginResponseMessage(flag, "用户名或密码错误");
        }
        channelHandlerContext.writeAndFlush(responseMessage);
    }
}
